<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>简易BBS论坛</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .auth-section {
            background: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        #commentForm {
            background: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .comment {
            background: white;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            position: relative;
        }
        .comment-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            align-items: center;
        }
        .comment-author {
            font-weight: bold;
            color: #333;
        }
        .comment-time {
            color: #666;
            font-size: 0.9em;
        }
        .comment-content {
            margin: 10px 0;
            line-height: 1.5;
        }
        .comment-actions {
            margin-top: 10px;
        }
        .reply-form {
            margin-top: 15px;
            margin-left: 30px;
            padding-left: 15px;
            border-left: 3px solid #eee;
        }
        .reply {
            margin-top: 10px;
            margin-left: 30px;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 3px;
        }
        input, textarea, button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            margin-left: 5px;
        }
        button:hover {
            background: #45a049;
        }
        button.edit-btn {
            background: #2196F3;
        }
        button.delete-btn {
            background: #f44336;
        }
        .logged-in-only {
            display: none;
        }
        body.logged-in .logged-in-only {
            display: block;
        }
        body.logged-in .logged-out-only {
            display: none;
        }
    </style>
</head>
<body>
    <h1>简易BBS论坛</h1>
    
    <!-- 登录/登出区域 -->
    <div class="auth-section">
        <div id="loginArea" class="logged-out-only">
            <h3>用户登录</h3>
            <input type="text" id="usernameInput" placeholder="输入用户名">
            <button onclick="login()">登录</button>
        </div>
        <div id="userInfo" class="logged-in-only">
            <h3>欢迎, <span id="currentUser"></span></h3>
            <button onclick="logout()">登出</button>
        </div>
    </div>
    
    <!-- 评论表单 -->
    <div id="commentForm" class="logged-in-only">
        <h3>发表评论</h3>
        <textarea id="contentInput" placeholder="写下你的想法..." rows="3" style="width: 100%;"></textarea>
        <button onclick="submitComment()">发表评论</button>
    </div>
    
    <!-- 评论列表 -->
    <div id="commentList">
        <h3>所有评论</h3>
        <div id="commentsContainer"></div>
    </div>

    <div id="replyForm-${comment.id}" class="reply-form logged-in-only" style="display: none;">
        <textarea id="replyContent-${comment.id}" placeholder="写下你的回复..." rows="2" style="width: 100%;"></textarea>
        <button onclick="submitReply('${comment.id}')">发表回复</button>
        <button onclick="toggleReplyForm('${comment.id}')">取消</button>
    </div>

    <script>
        // 检查登录状态
        async function checkLogin() {
            try {
                const response = await fetch('/api/current_user');
                const user = await response.json();
                
                if (user.username) {
                    document.body.classList.add('logged-in');
                    document.getElementById('currentUser').textContent = user.username;
                } else {
                    document.body.classList.remove('logged-in');
                }
                
                fetchComments(); // 刷新评论列表
            } catch (error) {
                console.error('检查登录状态失败:', error);
            }
        }
        
        // 登录功能
        async function login() {
            const username = document.getElementById('usernameInput').value.trim();
            
            if (!username) {
                alert('请输入用户名');
                return;
            }
            
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username })
                });
                
                if (response.ok) {
                    document.getElementById('usernameInput').value = '';
                    checkLogin();
                } else {
                    const error = await response.json();
                    alert(error.error || '登录失败');
                }
            } catch (error) {
                console.error('登录失败:', error);
                alert('登录失败，请检查网络连接');
            }
        }
        
        // 登出功能
        async function logout() {
            try {
                const response = await fetch('/api/logout', { method: 'POST' });
                
                if (response.ok) {
                    checkLogin();
                } else {
                    alert('登出失败');
                }
            } catch (error) {
                console.error('登出失败:', error);
            }
        }
        
        // 获取评论列表
        async function fetchComments() {
            try {
                const response = await fetch('/api/comments');
                const comments = await response.json();
                renderComments(comments);
            } catch (error) {
                console.error('获取评论失败:', error);
            }
        }
        
        // 渲染评论列表
        function renderComments(comments) {
            const container = document.getElementById('commentsContainer');
            container.innerHTML = '';
            
            if (comments.length === 0) {
                container.innerHTML = '<p>暂无评论，快来发表第一条吧！</p>';
                return;
            }
            
            comments.forEach(comment => {
                const commentElement = createCommentElement(comment);
                container.appendChild(commentElement);
                
                // 加载回复
                fetchReplies(comment.id);
            });
        }
        
        // 创建单个评论元素
        function createCommentElement(comment) {
            const isCurrentUser = document.getElementById('currentUser')?.textContent === comment.author;
            
            const commentDiv = document.createElement('div');
            commentDiv.className = 'comment';
            commentDiv.dataset.id = comment.id;
            
            commentDiv.innerHTML = `
                <div class="comment-header">
                    <span class="comment-author">${comment.author}</span>
                    <span class="comment-time">${formatTime(comment.timestamp)}</span>
                </div>
                <div class="comment-content">${comment.content}</div>
                <div class="comment-actions logged-in-only">
                    ${isCurrentUser ? `
                        <button class="edit-btn" onclick="startEditComment('${comment.id}')">编辑</button>
                        <button class="delete-btn" onclick="deleteComment('${comment.id}')">删除</button>
                    ` : ''}
                    <button onclick="toggleReplyForm('${comment.id}')">回复</button>
                </div>
                <div id="replyForm-${comment.id}" class="reply-form logged-in-only" style="display: none;">
                    <textarea id="replyContent-${comment.id}" placeholder="写下你的回复..." rows="2" style="width: 100%;"></textarea>
                    <button onclick="submitReply('${comment.id}')">发表回复</button>
                    <button onclick="toggleReplyForm('${comment.id}')">取消</button>
                </div>
                <div id="replies-${comment.id}" class="replies"></div>
            `;
            
            return commentDiv;
        }
        
        // 提交评论
        async function submitComment() {
            const content = document.getElementById('contentInput').value.trim();
            
            if (!content) {
                alert('请输入评论内容');
                return;
            }
            
            try {
                const response = await fetch('/api/comments', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ content })
                });
                
                if (response.ok) {
                    document.getElementById('contentInput').value = '';
                    fetchComments();
                } else {
                    const error = await response.json();
                    alert(error.error || '发表评论失败');
                }
            } catch (error) {
                console.error('发表评论失败:', error);
                alert('发表评论失败，请检查网络连接');
            }
        }
        
        // 开始编辑评论
        function startEditComment(commentId) {
            const commentDiv = document.querySelector(`.comment[data-id="${commentId}"]`);
            const contentElement = commentDiv.querySelector('.comment-content');
            const originalContent = contentElement.textContent;
            
            contentElement.innerHTML = `
                <textarea id="editContent-${commentId}" style="width: 100%; height: 100px;">${originalContent}</textarea>
                <button onclick="saveEdit('${commentId}')">保存</button>
                <button onclick="cancelEdit('${commentId}')">取消</button>
            `;
        }
        
        // 保存编辑
        async function saveEdit(commentId) {
            const commentDiv = document.querySelector(`.comment[data-id="${commentId}"]`);
            const textarea = commentDiv.querySelector(`#editContent-${commentId}`);
            const newContent = textarea.value.trim();
            
            if (!newContent) {
                alert('评论内容不能为空');
                return;
            }
            
            try {
                const response = await fetch(`/api/comments/${commentId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ content: newContent })
                });
                
                if (response.ok) {
                    fetchComments();
                } else {
                    const error = await response.json();
                    alert(error.error || '编辑评论失败');
                }
            } catch (error) {
                console.error('编辑评论失败:', error);
                alert('编辑评论失败，请检查网络连接');
            }
        }
        
        // 取消编辑
        function cancelEdit(commentId) {
            fetchComments(); // 直接重新加载评论
        }
        
        // 删除评论
        async function deleteComment(commentId) {
            if (!confirm('确定要删除这条评论吗？')) return;
            
            try {
                const response = await fetch(`/api/comments/${commentId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    fetchComments();
                } else {
                    const error = await response.json();
                    alert(error.error || '删除评论失败');
                }
            } catch (error) {
                console.error('删除评论失败:', error);
                alert('删除评论失败，请检查网络连接');
            }
        }
        
        // 显示/隐藏回复表单
        function toggleReplyForm(commentId) {
            const form = document.getElementById(`replyForm-${commentId}`);
            form.style.display = form.style.display === 'none' ? 'block' : 'none';
        }
        
        // 提交回复
        async function submitReply(parentId) {
        const content = document.getElementById(`replyContent-${parentId}`).value.trim();
        
        if (!content) {
            alert('请输入回复内容');
            return;
        }
        
        try {
            const response = await fetch(`/api/comments/${parentId}/replies`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ content: content })
            });
            
            if (response.ok) {
                document.getElementById(`replyContent-${parentId}`).value = '';
                toggleReplyForm(parentId);
                fetchReplies(parentId);
            } else {
                const error = await response.json();
                alert(error.error || '发表回复失败: ' + response.status);
            }
        } catch (error) {
            console.error('发表回复失败:', error);
            alert('发表回复失败，请检查网络连接');
        }
    }
        
        // 获取回复列表
        async function fetchReplies(parentId) {
            try {
                const response = await fetch(`/api/comments/${parentId}/replies`);
                const replies = await response.json();
                renderReplies(parentId, replies);
            } catch (error) {
                console.error('获取回复失败:', error);
            }
        }
        
        // 渲染回复列表
        function renderReplies(parentId, replies) {
            const container = document.getElementById(`replies-${parentId}`);
            container.innerHTML = '';
            
            if (replies.length === 0) return;
            
            replies.forEach(reply => {
                const replyElement = document.createElement('div');
                replyElement.className = 'reply';
                replyElement.innerHTML = `
                    <div class="comment-header">
                        <span class="comment-author">${reply.author}</span>
                        <span class="comment-time">${formatTime(reply.timestamp)}</span>
                    </div>
                    <div class="comment-content">${reply.content}</div>
                `;
                container.appendChild(replyElement);
            });
        }
        
        // 格式化时间
        function formatTime(isoString) {
            const date = new Date(isoString);
            return date.toLocaleString();
        }
        
        // 初始化页面
        window.onload = checkLogin;
    </script>
</body>
</html>